package com.example.administrator.viewpager;

import android.os.Bundle;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.administrator.myfragment.R;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;


public class TabLayoutActivity extends FragmentActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;

    List<Fragment> fragments = new ArrayList<>();//步骤1：创建存储多个Fragment实例的列表
    List<String> titles = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_viewpager);

        tabLayout = (TabLayout) findViewById(R.id.tl_tabs);
        viewPager = (ViewPager) findViewById(R.id.vp_content);
//60  169  269  529
        fragments.add(new MyFragment("11111", "60"));
        fragments.add(new MyFragment("22222", "169"));
        fragments.add(new MyFragment("33333", "269"));
        fragments.add(new MyFragment("44444", "529"));
        titles.add("fragment1");
        titles.add("fragment2");
        titles.add("fragment3");
        titles.add("fragment4");
        //步骤2：创建PagerAdapter实例并关联到Viewpager中
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
//                super.destroyItem(container, position, object);
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });
//步骤3：将ViewPager关联到Tablayout中
        tabLayout.setupWithViewPager(viewPager);
    }

}
